﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using EntityMap.Meta;
using System.Reflection;
using System.Collections;

namespace EntityMap
{
    public partial class EntityMapper
    {
        public object ExecuteStatement<T>( string statementId, object objParameter )
        {
            // create a context for execution
            Context context = new Context();
            context.Mapper = this;
            context.Parameter = objParameter;

            Type entityType = typeof( T );

            // recovery info
            EntityInfo einfo = this.GetEntityInfo( entityType );

            SqlStatement sqlStatement = einfo.GetStatement( statementId );      

            if( objParameter != null )
            {
                context.ParameterMap = einfo.GetParameterMap( sqlStatement.ParameterMap );               
            }

            if( sqlStatement is SelectStatement )
            {
                context.ResultMap = einfo.GetResultMap( ((SelectStatement)sqlStatement).ResultMap );
            }

            // fire event before
            if( OnExcutingStatement != null )
            {
                EntityMapEventArgs args = new EntityMapEventArgs( statementId, objParameter );
                OnExcutingStatement( this, args );
            }

            if( _tw != null )
            {
                _tw.Write( sqlStatement.Command );
            }

            // execute statement
            object result = sqlStatement.Process<T>( context );

            // fire event after
            if( OnExcutedStatement != null )
            {
                EntityMapEventArgs args = new EntityMapEventArgs( statementId, objParameter );
                OnExcutedStatement( this, args );
            }

            return result;
        }
      
    }
}
